#include "OLDialog.h"
#include "OLButton.h"
#include "OLAppTemplateDefs.h"
#include "OLApplication.h"
#include "OLDialogTitle.h"

#include <QPainter>
#include <QVBoxLayout>
#include <QLabel>
#include <QHBoxLayout>

#define DIALOGBTN_ID "__dialog"

OLDialog::OLDialog(OLDialogTitle* title, QLayout* body, const OLButtonList& buttons, QWidget *parent) :
    QWidget(parent), m_dialogtitle(title)
{
    m_dialogtitle->setParent(this);

    m_body = new QWidget(this);
    m_body->setLayout(body);

//     all the buttons associated with dialog must given objectname=DIALOGBTN_ID, this
//     is so they can be identified later when drawing the separators and not mixed with
//     any buttons that may be provided in the body layout.
    foreach(OLButton* currentBtn, buttons) {
        currentBtn->setParent(this);
        currentBtn->opaque();
        currentBtn->setObjectName(DIALOGBTN_ID);
        currentBtn->setFixedHeight(FINGER_SIZE-10);
        m_buttons.append(currentBtn);
        connect(currentBtn, SIGNAL(clicked()), SIGNAL(dismissDialog()));
    }

    if(OLApp->orientation()==OLApplication::portrait)
        handlePortrait();
    else
        handleLandscape();
}

void OLDialog::handlePortrait()
{
    delete layout();
    QVBoxLayout* mainLayout = new QVBoxLayout();
    mainLayout->setContentsMargins(30, 10, 30, 10);
    mainLayout->setSpacing(5);
    mainLayout->addStretch();
    mainLayout->addWidget(m_dialogtitle);
    mainLayout->addWidget(m_body);
    foreach(OLButton* btn, m_buttons) {
        mainLayout->addWidget(btn);
    }
    mainLayout->addStretch();
    setLayout(mainLayout);
}

void OLDialog::handleLandscape()
{
    delete layout();

    QVBoxLayout* mainLayout = new QVBoxLayout();
    mainLayout->setContentsMargins(30, 10, 30, 10);
    mainLayout->setSpacing(5);
    mainLayout->addStretch();
    mainLayout->addWidget(m_dialogtitle);
    mainLayout->addWidget(m_body);

    if(m_buttons.count()) {
        QHBoxLayout* btnLayout = new QHBoxLayout();
        btnLayout->setMargin(0);
        btnLayout->setSpacing(5);

        foreach(OLButton* btn, m_buttons) {
            btnLayout->addWidget(btn);
        }
        mainLayout->addLayout(btnLayout);
    }

    mainLayout->addStretch();

    setLayout(mainLayout);
}
